package com.sqx.modules.creditRecord.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.ShiroUtils;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.creditRecord.dao.CreditRecordDao;
import com.sqx.modules.creditRecord.entity.CreditRecord;
import com.sqx.modules.creditRecord.service.CreditRecordService;
import com.sqx.modules.sys.entity.SysUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author www.javacoder.top
 * @since 2023-05-17
 */
@Service
public class CreditRecordServiceImpl extends ServiceImpl<CreditRecordDao, CreditRecord> implements CreditRecordService {

    @Autowired
    private UserService userService;

    @Override
    public IPage<CreditRecord> getCreditRecordList(Integer page, Integer limit, CreditRecord creditRecord) {
        Page<CreditRecord> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.selectPage(pages, new QueryWrapper<>(creditRecord).orderByDesc("create_time"));
    }

    @Override
    public void updateUserCreditRecord(UserEntity userEntity, Integer type, Integer score, String remark) {
        CreditRecord creditRecord = new CreditRecord();
        creditRecord.setCreateTime(LocalDateTime.now());
        creditRecord.setLastCreditScore(userEntity.getCreditScore());
        creditRecord.setType(type);
        creditRecord.setRiderUserId(userEntity.getUserId());
        creditRecord.setRiderPhone(userEntity.getPhone());
        creditRecord.setRiderUserName(userEntity.getUserName());
        creditRecord.setNum(score);
        int nowScore;
        if (type == 1) {
            nowScore = userEntity.getCreditScore() + score;
        } else {
            nowScore = userEntity.getCreditScore() - score;
        }
        creditRecord.setNextCreditScore(nowScore);
        SysUserEntity sysUserEntity = ShiroUtils.getUserEntity();
        if (sysUserEntity!=null){
            creditRecord.setSysUserId(sysUserEntity.getUserId());
            creditRecord.setSysUserName(sysUserEntity.getUsername());
        }else {
            creditRecord.setSysUserId(userEntity.getUserId());
            creditRecord.setSysUserName(userEntity.getUserName());
        }
        creditRecord.setReason(remark);
        baseMapper.insert(creditRecord);

        userEntity.setCreditScore(nowScore);
        userService.updateById(userEntity);
    }
}
